<?php


namespace App\logic;


use App\Models\Orders;
use App\Models\Visits;
use App\servers\AlipayServer;
use Illuminate\Support\Facades\DB;

class OrderServer
{
    /**
     * 生成订单
     */
    public static function addOrder($data)
    {
        $vwhere = [
          ['user_id',$data['uid']],
          ['status',0,]
        ];
        $visitor = Visits::getVisit($vwhere);
        if(!$visitor) abort(101,'请不要重复下单');
        //添加复诊表信息
        $visData = self::addVisData($data);
        //生成订单表
        $orderData = self::addOrderInfo($data);
        //处理事务死锁
        DB::transaction(function () use ($visData, $orderData) {
            Visits::create($visData);
            Orders::create($orderData);
        }, 5);
        AlipayServer::alipay($orderData);


    }

    /**
     * @param $data
     */
    public static function addVisData($params)
    {
        //时间转时间戳
        $dateTime = strtotime($params['date'] . $params['time']);
        $data = [
            'user_id' => $params['uid'],
            'doctor_id' => $params['doctor_id'],
            'datetime' => $dateTime,
            'status' => 0,
        ];
        return $data;
    }

    /**
     * 生成订单信息
     * @param $params
     */
    public static function addOrderInfo($params)
    {
        $order_sn = 'fz'.date('YmdHis').str_pad($params['uid'],10,0,STR_PAD_LEFT);
        $data = [
            'order_sn' => $order_sn,
            'order_type' => $params['type'],
            'user_id' => $params['uid'],
            'status' => 0,
            'money' => $params['money']
        ];
        return $data;
    }
}
